import json
from typing import List, Union

import requests
from yagmail import SMTP

from setting import config
from core.logger import logger


class Message(object):

    # 发送邮件
    @staticmethod
    def send_email(host=config.EMAIL_HOST, port=config.EMAIL_PORT, smtp_ssl=True, user=config.EMAIL_USERNAME,
                   password=config.EMAIL_PASSWORD, email_name=None, subject='test email', body='', html='', img=''):
        if email_name is None:
            email_name = ["sa@welab-inc.com"]
        yag = SMTP(host=host, user=user, password=password, port=port, smtp_ssl=smtp_ssl)
        try:
            yag.send(email_name, subject, contents=[body, html, img])
            logger.info(f"{subject}:  邮箱发送成功")
            return True
        except Exception as e:
            logger.error(f"{subject}: 邮箱发送失败 => {e}")
        return False

    @staticmethod
    def send_wechat_users(user: List, content: str, timeout=5):
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Basic eXVud2VpLmFwaTpDcWhUY2ZvOTZSNUE=}'
        }
        data = json.dumps({'config': {'user_list': user, 'content': content}})
        res = requests.post('https://sa.welab-inc.com/api/tasks/wechat/send', data=data, headers=headers,
                            timeout=timeout)
        res.encoding = 'utf-8'
        return res.text

    @staticmethod
    def send_wechat_group(group_id: str, content: str, timeout: int = 5):
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Basic eXVud2VpLmFwaTpDcWhUY2ZvOTZSNUE=}'
        }
        data = json.dumps({'config': {'chat_id': group_id, 'content': content}})
        res = requests.post('https://sa.welab-inc.com//api/tasks/wechat/push', data=data, headers=headers,
                            timeout=timeout)
        res.encoding = 'utf-8'
        return res.text

    # # 发送短信
    # @staticmethod
    # def send_ali_sms(phone_number, sms_message):
    #     from aliyunsdkcore.client import AcsClient
    #     from aliyunsdkcore.request import CommonRequest
    #     client = AcsClient('LTAIxOJMZmWslh0B', 'Y2SgKBQKWDHka4mzNQHTdo3DwS6sWQ', 'cn-shenzhen')
    #
    #     request = CommonRequest()
    #     request.set_accept_format('json')
    #     request.set_domain('dysmsapi.aliyuncs.com')
    #     request.set_method('POST')
    #     request.set_version('2017-05-25')
    #     request.set_action_name('SendSms')
    #
    #     request.add_query_param('PhoneNumbers', phone_number)
    #     request.add_query_param('SignName', '卫盈智信')
    #     request.add_query_param('TemplateCode', 'SMS_157100121')
    #     request.add_query_param('TemplateParam', f'{{"message":"{sms_message}"}}')
    #
    #     response = client.do_action_with_exception(request)
    #     print(response)
    #     # logger.info('发送短信告警响应结果：', str(response, encoding='utf-8'))
    #
    # # 发送语音
    # @staticmethod
    # def send_voice(mobile, text="你好，我来贷生产环境出现问题啦，请紧急处理，谢谢。"):
    #     url = "https://sa.wolaidai.com/api/tasks/voice/send"
    #     headers = {
    #         'content-type': "application/json",
    #         'authorization': "cWkuemhhbmc6enEuOTQwODAy"
    #     }
    #     payload = json.dumps({'users': [{'username': 'yunwei', 'mobile': mobile}],
    #                           "text": text})
    #     response = requests.request("POST", url, data=payload, headers=headers)
    #
    #     logger.info(f'语音告警通知”{mobile}“的响应为{response.text}')
    #     return response.text


if __name__ == '__main__':
    Message.send_email()
#     # Message.send_wechat_users(['boll.lai'], "test")
#     from core.logger import logger
#
#     from common.kibana import Kibana
#     from common.elastic import get_es
#     from common.database import SessionLocal
#     from app.monitor_logs.utils import ServiceLogs
#     from pprint import pprint
#
#     kibana = Kibana(host='106.52.172.23', username='elastic', password='q5f2qNfUJQyvZPIz57MZ')
#     pprint(kibana.get_index_pattern_ids())
#     # pprint(requote_uri("Something Cool"))
#
#     k_url = kibana.get_error_log_app_url('34118c30-82a6-11ec-a335-a14a62acd312', 'thirdparty-sync',
#                                          '2022-01-28T16:00:00.000Z', '2022-01-29T16:00:00.000Z',
#                                          ['java.lang.NullPointerException',
#                                           'com.welab.thirdparty.sync.exception.ThirdpartySyncException'])
